<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace app\helper;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\exception\HttpException;

/**
 * Undocumented class
 */
class Ident
{
    public static function token($data = []) : string
    {
        $time = time(); //当前时间
        $payload = [
            'iss' => request()->host(), //签发者 可选
            'aud' => request()->host(), //接收该JWT的一方，可选
            'iat' => $time, //签发时间
            'nbf' => $time , //(Not Before)：某个时间点后才能访问，比如设置time+30，表示当前时间30秒后才能使用
            'exp' => $time + 3600 * 24 * 30, //过期时间,这里设置2个小时
            'data' => $data //自定义信息，不要定义敏感信息
        ];
        // 获取token
        return JWT::encode($payload, config('jwt.key'), config('jwt.method')); //参数为用户认证的信息，请自行添加
    }

    public static function auth(string $key = 'token'){
        $jwt = request()->header($key) ?: '';
        if(empty($jwt)){
            throw new HttpException(401, '请登录');
        }
        try{
            $payload = JWT::decode($jwt, new Key(config('jwt.key'), config('jwt.method')));
            return $payload->data;
        } catch(\HttpException $e){
            throw new \HttpException($e->getMessage(), 401);
        }
    }
}
